package edu.hawaii.myisern.action;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Ensures that the user is logged in before allowing access to secured pages.
 * 
 * @author Tim Fennell
 * @author Ed Kim
 * @author Jon Lao
 * @author JianFei Liao
 * @author Jared Sunouchi
 */
public class SecurityFilter implements Filter {
  private static Set<String> publicUrls = new HashSet<String>();

  static {
    publicUrls.add("/index.jsp");
    publicUrls.add("/Index.action");
  }

  /**
   * Does nothing.
   * 
   * @param filterConfig configuration
   * @throws ServletException if error encountered.
   */
  public void init(FilterConfig filterConfig) throws ServletException {
    // Does nothing.
  }

  /**
   * Checks if user is logged in before letting page display.
   * 
   * @param servletRequest requesting servlet
   * @param servletResponse response from servlet
   * @param filterChain used by stripes
   * @throws ServletException if error encountered.
   * @throws IOException if io error encountered.
   */
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    
    if (request.getSession().getAttribute("user") == null) {
      
      if (isPublicResource(request)) {
        filterChain.doFilter(request, response);
      }
      else {
        response.sendRedirect(request.getContextPath() + "/index.jsp");
      }
    }
    
    else {
      filterChain.doFilter(request, response);
    }
}

  /**
   * Method that checks the request to see if it is for a publicly accessible resource.
   * 
   * @param request servlet request.
   * @return true if public.
   */
  protected boolean isPublicResource(HttpServletRequest request) {
    return publicUrls.contains(request.getServletPath());
  }

  /** Does nothing. */
  public void destroy() {
    // Does nothing.
  }
}
